
import {Base} from '../../utils/base.js';

class Order extends Base {

  constructor(){
    super();
    this._storageKeyName = 'newOrder';
  }

  //向服务器发起请求-下订单
  //param 订单商品信息
  doOrder(param, callback){
    var that = this;
    var allParams = {
      url: 'order',
      type: 'POST',
      data: {products: param},
      successCallback:function(data){
        that.execSetStorageSync(true);
        callback && callback(data)
      },
      errorCallback:function(){
      }
    }

    this.request(allParams);
  }

  /**
   * 调用服务器支付接口获得拉起微信支付的参数
   * @param:
   * orderNumber - {int} 订单id
   * return:
   * callback - {obj}回调方法。
   * 返回参数：
   * 0 - 商品缺货等原因导致订单不能支付。
   * 1 -支付失败或支付取消
   * 2 - 支付成功
   */
  execPay(orderNumber, callback){
    var allParams = {
      url: 'pay/pre_order',
      type: 'POST',
      data: {id: orderNumber},
      successCallback:function(data){
        //成功则服务器返回拉起微信支付需要的参数
        var timeStamp = data.timeStamp;
        if(timeStamp){
          wx.requestPayment({
            timeStamp: timeStamp.toString(),
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.paySign,
            success:function(){
              callback && callback(2); 
            },
            fail:function(){
              callback && callback(1); 
            }
          })
        }else{
          callback && callback(0); 
        }
      },
      errorCallback:function(data){
        //
      }
    }

    this.request(allParams);
  }

  //获取订单详情信息
  getOrderInfoById(id, callback){
    var params = {
      url: 'order/' + id,
      successCallback: function(data){
        callback && callback(data);
      },
      errorCallback:function(data){
        //
      }
    }
    this.request(params);
  }

  //获取订单列表，pagesIndex 从1开始 第几页
  getOrders(pagesIndex, callback){
    var allParams = {
      url: 'order/by_user',
      data: {page: pagesIndex},
      successCallback:function(data){
        callback && callback(data);
      }
    };
    this.request(allParams);
  }

  //本地缓存 保存/更新
  execSetStorageSync(data){
    wx.setStorageSync(this._storageKeyName, data)
  }

  //判断是否有新订单
  hasNewOrder(data){
    var flag = wx.getStorageSync(this._storageKeyName);
    return flag == true;
  }

}

export {Order};